package com.party.admin.web.controller.crowdfund;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.admin.biz.activity.ActivityDeleteBizService;
import com.party.admin.biz.circle.CircleBizNewService;
import com.party.admin.biz.crowdfund.CrowdfundEventBizService;
import com.party.admin.biz.file.ExcelExportService;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.gatherInfo.ItineraryBizService;
import com.party.admin.biz.system.MemberBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.utils.excel.ExportExcel;
import com.party.admin.web.annotation.UserOperate;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.DateUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.*;
import com.party.core.model.audio.Audio;
import com.party.core.model.city.City;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.crowdfund.CrowdfundEventWithMemberPartner;
import com.party.core.model.crowdfund.EventGradation;
import com.party.core.model.log.BehaviorType;
import com.party.core.model.member.MemberAct;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.partner.MemberPartner;
import com.party.core.service.activity.IActivityDetailService;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.ICrowfundResourcesService;
import com.party.core.service.activity.biz.ActivityDetailBizService;
import com.party.core.service.activity.biz.CrowfundResourceBizService;
import com.party.core.service.audio.IAudioService;
import com.party.core.service.circle.biz.CircleBizService;
import com.party.core.service.circle.biz.CircleMemberBizService;
import com.party.core.service.city.ICityService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.counterfoil.biz.CounterfoilBizService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IEventGradationService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.gatherInfo.biz.GatherInfoMembersBizService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IMemberAdministratorService;
import com.party.core.service.member.IMemberGroupInfoService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.util.MemberFormUtil;
import com.party.core.service.partner.IMemberPartnerService;
import com.party.core.utils.MyBeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 众筹事件控制器
 * Created by wei.li
 *
 * @date 2017/4/26 0026
 * @time 14:04
 */

@SuppressWarnings("all")
@Controller
@RequestMapping(value = "crowdfund/event")
public class CrowdfundEventController {

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IMemberActService memberActService;
    @Autowired
    private CircleMemberBizService circleMemberBizService;
    @Autowired
    private CircleBizService circleBizService;
    @Autowired
    private GatherInfoMembersBizService gatherInfoMembersBizService;
    @Autowired
    private ICrowfundResourcesService crowfundResourcesService;
    @Autowired
    private CrowfundResourceBizService crowfundResourceBizService;
    @Autowired
    private IActivityDetailService activityDetailService;
    @Autowired
    private IMemberPartnerService memberPartnerService;
    @Autowired
    private ActivityDetailBizService activityDetailBizService;
    @Autowired
    private ICityService cityService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private ActivityDeleteBizService activityDeleteBizService;
    @Autowired
    private ItineraryBizService itineraryBizService;
    @Autowired
    private CircleBizNewService circleBizNewService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private IMemberGroupInfoService memberGroupInfoService;
    @Autowired
    private CrowdfundEventBizService crowdfundEventBizService;
    @Autowired
    private ExcelExportService excelExportService;
    @Autowired
    private IMemberAdministratorService memberAdministratorService;
    @Autowired
    private IAudioService audioService;
    @Autowired
    private IEventGradationService eventGradationService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private CounterfoilBizService counterfoilBizService;
    @Autowired
    private ICounterfoilService counterfoilService;
    @Autowired
    private IMemberGroupService memberGroupService;

    protected static Logger logger = LoggerFactory.getLogger(CrowdfundEventController.class);


    /**
     * 众筹事件列表
     *
     * @param crowdfundEvent 众筹事件
     * @param page           分页参数
     * @return 事件列表
     */
    @RequestMapping(value = "list")
    public ModelAndView list(CrowdfundEventWithMemberPartner crowdfundEvent, Page page, CommonInput input) {
        page.setLimit(20);
        ModelAndView modelAndView = new ModelAndView("crowdfund/eventList");
        Map<String, Object> param = CommonInput.appendParams(input);
        param.put("openStatus", 1);
        //crowdfundEvent.setCheckStatus(1);
        Map<String, Object> params = RealmUtils.getMemberAdministrator(param, memberAdministratorService);

        crowdfundEvent.setIsMultiple(YesNoStatus.NO.getCode());
        List<CrowdfundEventWithMemberPartner> crowdfundEventList = crowdfundEventService.webListPage(crowdfundEvent, params, page);
        for (CrowdfundEventWithMemberPartner event : crowdfundEventList) {
            Integer crowdfundNum = activityService.getCountByEventId(event.getId());
            event.setCrowdfundNum(crowdfundNum);

            // 众筹联合发起二维码
            String filePath = fileBizService.getUploadCIPath(event.getCreateBy(), "zcEvent");
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + event.getId());
            event.setBindQrCode(qrCodeUrl);
        }

        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, "2018-05-04".length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, "2018-05-04".length()));
        }

        modelAndView.addObject("list", crowdfundEventList);
        modelAndView.addObject("page", page);
        modelAndView.addObject("input", input);
        modelAndView.addObject("event", crowdfundEvent);
        return modelAndView;
    }


    /**
     * 众筹主题审核列表
     *
     * @param crowdfundEvent 众筹事件
     * @param page           分页参数
     * @return 事件列表
     */
    @RequestMapping(value = "checkList")
    public ModelAndView checkList(CrowdfundEventWithMemberPartner crowdfundEvent, Page page, CommonInput input) {
        page.setLimit(20);
        ModelAndView modelAndView = new ModelAndView("crowdfund/eventCheckList");
        Map<String, Object> params = CommonInput.appendParams(input);
        params.put("openStatus", 1);

        List<CrowdfundEventWithMemberPartner> crowdfundEventList = crowdfundEventService.webListPage(crowdfundEvent, params, page);

        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, "2018-05-04".length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, "2018-05-04".length()));
        }

        modelAndView.addObject("list", crowdfundEventList);
        modelAndView.addObject("page", page);
        modelAndView.addObject("input", input);
        modelAndView.addObject("event", crowdfundEvent);
        return modelAndView;
    }


    @RequestMapping(value = "eventDetail")
    public ModelAndView eventDetail(String eventId) {
        ModelAndView mv = new ModelAndView("crowdfund/eventDetail");
        if (StringUtils.isBlank(eventId)) {
            return null;
        }
        CrowdfundEvent event = crowdfundEventService.get(eventId);
        ActivityDetail activityDetail = activityDetailService.getByRefId(eventId);//获取当前主题的详情、报名相关、参赛标准
        if (activityDetail != null) {
            activityDetailBizService.castToHTML(activityDetail);
        }
        //地址
        String address = crowdfundEventService.getShowAddress(event);
        Integer viewNum = projectService.viewNumForEventId(eventId);
        mv.addObject("eventCount", crowdfundEventService.getEventCountResult(eventId));
        mv.addObject("event", event);
        mv.addObject("eventDetail", activityDetail);
        mv.addObject("address", address);
        mv.addObject("viewNum", viewNum);
        return mv;
    }

    /**
     * 众筹事件视图
     *
     * @param id 事件编号
     * @return 众筹事件
     */
    @RequestMapping(value = "view")
    public ModelAndView view(String id) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/eventView");
        City city = new City();
        city.setIsOpen(1);
        modelAndView.addObject("citys", cityService.list(city));


        List<Audio> audioList = null;
        //背景乐
        try {
            audioList = audioService.list(new Audio(null, com.party.common.constant.Constant.IS_CROWDFUNDED, null));
        } catch (Exception e) {
            logger.info("众筹主题详情页————获取背景乐列表失败", e.getMessage());
        }
        modelAndView.addObject("audioList", audioList);


        if (!Strings.isNullOrEmpty(id)) {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(id);
            if (StringUtils.isNotEmpty(crowdfundEvent.getSupportRange())) {
                if (crowdfundEvent.getSwitchSupportRange() == 3) {
                    String[] ranges = crowdfundEvent.getSupportRange().split(",");
                    crowdfundEvent.setRangeStart(Integer.valueOf(ranges[0]));
                    crowdfundEvent.setRangeEnd(Integer.valueOf(ranges[1]));
                    crowdfundEvent.setSupportRange("");
                }
            }

            City c = cityService.get(crowdfundEvent.getCityId());
            if (null != c) {
                modelAndView.addObject("cityName", c.getName());
            }
            Counterfoil t = new Counterfoil();
            t.setBusinessId(id);
            List<Counterfoil> counterfoils = counterfoilService.list(t);
            for (Counterfoil counterfoil : counterfoils) {
                if (counterfoil.getJoinNum() > 0) {
                    counterfoil.setHasBuy(true);
                }
            }
            modelAndView.addObject("counterfoils", counterfoils);
            // 跑马灯
            List<CrowfundResources> picList = crowfundResourcesService.findByRefId(crowdfundEvent.getId(), "1");
            modelAndView.addObject("picList", picList);
            // 视频
            List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(crowdfundEvent.getId(), "2");
            if (videoList.size() > 0) {
                modelAndView.addObject("video", videoList.get(0));
            }

            /** 活动详情 **/
            ActivityDetail activityDetail = activityDetailService.getByRefId(crowdfundEvent.getId());
            if (activityDetail != null) {
                activityDetailBizService.castToHTML(activityDetail);
            }
            modelAndView.addObject("activityDetail", activityDetail);
            modelAndView.addObject("event", crowdfundEvent);

            Activity activity = activityService.countForEventId(id);
            modelAndView.addObject("eventActivity", activity);
        }
        return modelAndView;
    }


    /**
     * 保存众筹
     *
     * @param event 众筹事件
     * @return 保存结果
     */
    @ResponseBody
    @RequestMapping(value = "save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(CrowdfundEvent event, BindingResult result, ActivityInput input, ActivityDetail activityDetail) {
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }
        try {
            MemberGroup member = RealmUtils.getCurrentUser();

            if (StringUtils.isNotEmpty(input.getStartDate())) {
                event.setStartTime(DateUtils.parse(input.getStartDate(), "yyyy-MM-dd HH:mm"));
            }
            if (StringUtils.isNotEmpty(input.getEndDate())) {
                event.setEndTime(DateUtils.parse(input.getEndDate(), "yyyy-MM-dd HH:mm"));
            }
            if (StringUtils.isNotEmpty(input.getAreaInput())) {
                event.setArea(input.getAreaInput());
            }
            if (StringUtils.isNotEmpty(input.getAreaSelect())) {
                event.setArea(input.getAreaSelect());
            }

            if (event.getSwitchSupportRange() == 3) {
                event.setSupportRange(event.getRangeStart().toString() + "," + event.getRangeEnd().toString());
            } else if (event.getSwitchSupportRange() == 1) {
                event.setSupportRange("");
            }

            event.setUpdateBy(event.getCreateBy());

            String partnerId = memberGroupService.getPartnerId(event.getCreateBy());
            MemberPartner memberPartner = memberPartnerService.findByMemberId(partnerId);
            if (Strings.isNullOrEmpty(event.getId())) {
                if (memberPartner != null) {
                    //非系统客户提交的主题不需要审核直接通过
                    event.setCheckStatus(0);
                }
                // event.setCheckStatus(1);//默认为已审核
                crowdfundEventService.insert(event);

            } else {
                if (memberPartner != null && event.getCheckStatus() == 2) {
                    event.setCheckStatus(0);
                }

                event.setUpdateDate(new Date());
                crowdfundEventService.update(event);
            }

            /************* 详情 ****************/
            activityDetailBizService.saveBiz(event.getId(), activityDetail);
            crowfundResourceBizService.saveResourceBiz(event.getId(), input.getPicList(), input.getVideoList(), event.getCreateBy());

            List<Counterfoil> counterfoils1 = counterfoilBizService.saveBiz(event.getCounterfoils(), event.getId(), Constant.BUSINESS_TYPE_CROWDFUND, member.getId());

            if (StringUtils.isNotEmpty(event.getId())) {
                Activity activity = new Activity();
                activity.setEventId(event.getId());
                List<Activity> activities = activityService.list(activity);
                for (Activity act : activities) {
                    Float payment = 0f;
                    Integer limitNum = 0;
                    if (counterfoils1.size() > 0) {
                        payment = counterfoils1.get(0).getPayment();
                        limitNum = counterfoils1.get(0).getLimitNum();
                    } else {
                        payment = event.getPrice();
                        limitNum = event.getLimitNum();
                    }
                    act.setLimitNum(limitNum); // 人数上限
                    act.setPrice(payment); // 金额
                    act.setEndTime(event.getEndTime()); // 截止时间
                    act.setStartTime(event.getStartTime()); // 开始时间
                    act.setCityId(event.getCityId());
                    act.setArea(event.getArea());
                    act.setPlace(event.getPlace());
                    act.setLat(event.getLat());
                    act.setLng(event.getLng());
                    activityService.update(act);

                    activityDetailBizService.saveBizEvent(act.getId(), activityDetail);
                }
            }


            try {
                String filePath = fileBizService.getUploadCIPath(event.getCreateBy(), "zcEvent");
                String content = "project/bind_event.html?id=" + event.getId();
                fileBizService.uploadCloudOut(event.getId(), filePath, content, event.getCreateBy());
            } catch (Exception e) {
                logger.error("生成主题绑定手机二维码异常");
            }

            return AjaxResult.success("众筹主题保存成功", event.getId());
        } catch (Exception e) {
            logger.error("主题提交失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("");
        }
    }

    /**
     * 删除众筹事件
     *
     * @param id 事件编号
     * @return 删除结果
     */
    @ResponseBody
    @UserOperate(moduleName = "众筹/多场众筹主题", behaviorType = BehaviorType.DELETE)
    @RequestMapping(value = "delete")
    public AjaxResult delete(String id) {
        Activity activity = new Activity();
        activity.setEventId(id);
        activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        List<Activity> activities = activityService.list(activity);
        if (activities.size() > 0) {
            return AjaxResult.error("主题下已有项目，不能删除");
        }
        boolean flag = activityDeleteBizService.deleteEventBiz(id);
        if (flag) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 创建业务圈子
     *
     * @param eventId
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "createCircle")
    public AjaxResult createCircle(String eventId, String type) {
        try {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(eventId);
            Activity activity = new Activity();
            activity.setEventId(eventId);
            List<Activity> activities = activityService.list(activity);
            List<MemberAct> memberActs = new ArrayList<MemberAct>();
            for (Activity act : activities) {
                /*if (act.getMember().equals(act.getPublisher())) {
                    publishActivity = activityService.get(act.getId());
                }*/
                List<MemberAct> results = new ArrayList<MemberAct>();
                MemberAct memberAct = new MemberAct();
                memberAct.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                memberAct.setActId(act.getId());
                if (type.equals("1")) { // 已成功
                    memberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode());
                    results = memberActService.list(memberAct);
                } else if (type.equals("2")) { // 全部
                    Set<Integer> status = new HashSet<Integer>();
                    // status.add(ActStatus.ACT_STATUS_CANCEL.getCode());
                    // status.add(ActStatus.ACT_STATUS_NO_JOIN.getCode());
                    results = memberActService.getSuccessMemberAct(memberAct, status);
                }

                memberActs.addAll(results);
            }

            List<String> memberIds = new ArrayList<String>();
            memberIds.add(crowdfundEvent.getCreateBy());

            Activity publishActivity = new Activity();
            String remarks = crowdfundEvent.getName() + "——" + (type.equals("1") ? "已众筹成功人员圈子" : "全部发起众筹人员圈子");
            publishActivity.setTitle(crowdfundEvent.getName());
            publishActivity.setPic(crowdfundEvent.getPic());
            publishActivity.setRemarks(remarks);
            publishActivity.setMember(crowdfundEvent.getCreateBy());
            String circleId = circleBizService.createCircleBusiness(eventId, publishActivity, type);
            circleMemberBizService.circleMemberManage(memberActs, circleId, type, memberIds, RealmUtils.getCurrentUser().getId());

            circleBizNewService.uploadQrCode(crowdfundEvent.getCreateBy(), circleId);

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("生成圈子异常", e);
            return AjaxResult.error("生成圈子异常");
        }
    }

    /**
     * 生成人员信息收集项目
     *
     * @param eventId 事项id
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "createGatherInfo")
    public AjaxResult createGatherInfo(String eventId, String type) {
        try {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(eventId);
            Activity activity = new Activity();
            activity.setEventId(eventId);
            List<Activity> activities = activityService.list(activity);
            List<MemberAct> memberActs = new ArrayList<MemberAct>();
            for (Activity act : activities) {
                /*if (act.getMember().equals(act.getPublisher())) {
                    publishActivity = activityService.get(act.getId());
                }*/
                List<MemberAct> results = new ArrayList<MemberAct>();
                MemberAct memberAct = new MemberAct();
                memberAct.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                memberAct.setActId(act.getId());
                if (type.equals("1")) { // 已成功
                    memberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode());
                    results = memberActService.list(memberAct);
                } else if (type.equals("2")) { // 全部
                    Set<Integer> status = new HashSet<Integer>();
                    // status.add(ActStatus.ACT_STATUS_CANCEL.getCode());
                    // status.add(ActStatus.ACT_STATUS_NO_JOIN.getCode());
                    results = memberActService.getSuccessMemberAct(memberAct, status);
                }

                memberActs.addAll(results);
            }

            Activity publishActivity = new Activity();
            String remarks = crowdfundEvent.getName() + "——" + (type.equals("1") ? "已众筹成功人员信息收集项目" : "全部发起众筹人员信息收集项目");
            publishActivity.setTitle(crowdfundEvent.getName());
            publishActivity.setPic(crowdfundEvent.getPic());
            publishActivity.setRemarks(remarks);
            publishActivity.setMember(crowdfundEvent.getCreateBy());
            String projectId = gatherInfoMembersBizService.createGatherInfoProjectBusiness(eventId, publishActivity, type, publishActivity.getMember());
            gatherInfoMembersBizService.addMember(projectId, memberActs, publishActivity.getMember());

            itineraryBizService.uploadQrCode(publishActivity.getMember(), projectId);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("生成人员信息收集项目异常", e);
            return AjaxResult.error("生成人员信息收集项目异常");
        }
    }

    /**
     * 初始化没有主题的众筹项目
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("initActivityNotEventId")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult initActivityNotEventId() {
        try {

            List<String> actIds = activityService.getOrgNotEventId();
            for (String actId : actIds) {
                Activity activity = activityService.get(actId);

                CrowdfundEvent crowdfundEvent = new CrowdfundEvent();
                try {
                    MyBeanUtils.copyBeanNotNull2Bean(activity, crowdfundEvent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                crowdfundEvent.setId(null);
                crowdfundEvent.setCreateDate(activity.getCreateDate());
                crowdfundEvent.setUpdateDate(activity.getCreateDate());
                crowdfundEvent.setName(activity.getTitle());
                crowdfundEvent.setCreateBy(activity.getMember());
                crowdfundEvent.setUpdateBy(activity.getMember());
                String eventId = crowdfundEventService.insert(crowdfundEvent);

                activity.setEventId(eventId);
                activity.setUpdateDate(null);
                activityService.update(activity);

                // 保存详情
                ActivityDetail activityDetail = activityDetailService.getByRefId(actId);
                if (activityDetail != null) {
                    activityDetailBizService.castToHTML(activityDetail);
                }
                activityDetailBizService.saveBiz(eventId, activityDetail);

                List<CrowfundResources> picList = crowfundResourcesService.findByRefId(actId, "1");
                List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(actId, "2");
                crowfundResourceBizService.saveResourceBiz(eventId, picList, videoList, activity.getMember());
            }
            return AjaxResult.success();
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 初始化数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("initData")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult initData() {
        try {
            List<CrowdfundEvent> events = crowdfundEventService.list(new CrowdfundEvent());
            for (CrowdfundEvent crowdfundEvent : events) {
                MemberGroup createBy = memberGroupService.get(crowdfundEvent.getCreateBy());
                Activity publishActivity = null;
                Activity activity = new Activity();
                activity.setEventId(crowdfundEvent.getId());
                List<Activity> activities = activityService.list(activity);
                for (Activity act : activities) {
                    if (createBy.getRealname().indexOf(act.getPublisher()) != -1) {
                        publishActivity = activityService.get(act.getId());
                        break;
                    }
                }

                if (publishActivity != null) {
                    crowdfundEvent.setPic(publishActivity.getPic()); // 海报
                    crowdfundEvent.setEndTime(publishActivity.getEndTime()); // 截止时间
                    crowdfundEvent.setStartTime(publishActivity.getStartTime()); // 开始时间
                    crowdfundEvent.setLimitNum(publishActivity.getLimitNum()); // 人数上限
                    crowdfundEvent.setPrice(publishActivity.getPrice()); // 金额
                    crowdfundEvent.setCrowdfundHintSwitch(publishActivity.getCrowdfundHintSwitch()); // 消息提醒开关
                    crowdfundEvent.setTemplateStyle(publishActivity.getTemplateStyle()); // 隐藏数据开关
                    crowdfundEvent.setCityId(publishActivity.getCityId()); // 城市id
                    crowdfundEvent.setArea(publishActivity.getArea()); // 区域
                    crowdfundEvent.setPlace(publishActivity.getPlace()); // 活动场所
                    crowdfundEvent.setLat(publishActivity.getLat()); // 纬度
                    crowdfundEvent.setLng(publishActivity.getLng()); // 经度
                    crowdfundEvent.setCrowdDeclaration(publishActivity.getCrowdDeclaration()); // 众筹宣言
                    crowdfundEvent.setRepresentDeclaration(publishActivity.getRepresentDeclaration()); // 联合发起宣言
                    crowdfundEvent.setSupportDeclaration(publishActivity.getSupportDeclaration()); // 支持宣言
                    crowdfundEvent.setRemarks(publishActivity.getRemarks()); // 活动描述
                    crowdfundEvent.setUpdateDate(null);
                    crowdfundEventService.update(crowdfundEvent);

                    // 跑马灯
                    List<CrowfundResources> picList = crowfundResourcesService.findByRefId(publishActivity.getId(), "1");
                    crowfundResourceBizService.initResource(picList, crowdfundEvent);
                    // 视频
                    List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(publishActivity.getId(), "2");
                    crowfundResourceBizService.initResource(videoList, crowdfundEvent);

                    ActivityDetail activityDetail = activityDetailService.getByRefId(publishActivity.getId());
                    if (activityDetail != null) {
                        ActivityDetail newDetail = new ActivityDetail();
                        MyBeanUtils.copyBeanNotNull2Bean(activityDetail, newDetail);
                        newDetail.setId(null);
                        newDetail.setCreateDate(null);
                        newDetail.setUpdateDate(null);
                        newDetail.setRefId(crowdfundEvent.getId());
                        activityDetailService.insert(newDetail);
                    }
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(e.getMessage());
        }
    }

    @RequestMapping("copyEvent")
    public ModelAndView copyEvent(String eventId) {
        ModelAndView modelAndView = new ModelAndView("activity/zcActivityFormNew");
        if (StringUtils.isNotEmpty(eventId)) {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(eventId);
            if (crowdfundEvent.getCheckStatus() == MemberPartner.PARTNER_TYPE_DEFAULT) {//防止前端篡改数据进行伪发布
                modelAndView.setViewName("redirect:/crowdfund/event/list.do");
                return modelAndView;
            }
            Activity activity = new Activity();
            try {
                MyBeanUtils.copyBeanNotNull2Bean(crowdfundEvent, activity);
            } catch (Exception e) {
                e.printStackTrace();
            }
            activity.setId(null);
            activity.setEventId(eventId);
            //个人众筹页状态，0:显示所属主题报名人员,1:显示该项目报名人员,2:不显示,默认显示主题报名人员
            activity.setPersonalPopularPageState(0);
            activity.setMember(crowdfundEvent.getCreateBy());
            activity.setTitle(crowdfundEvent.getName());

            MemberGroup createBy = memberGroupService.get(crowdfundEvent.getCreateBy());
            activity.setPublisher(createBy.getRealname());
            activity.setPublisherLogo(createBy.getLogo());

            // 跑马灯
            List<CrowfundResources> picList = crowfundResourcesService.findByRefId(crowdfundEvent.getId(), "1");
            modelAndView.addObject("picList", picList);
            // 视频
            List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(crowdfundEvent.getId(), "2");
            if (videoList.size() > 0) {
                modelAndView.addObject("video", videoList.get(0));
            }


            /** 活动详情 **/
            ActivityDetail activityDetail = activityDetailService.getByRefId(crowdfundEvent.getId());
            if (activityDetail != null) {
                activityDetailBizService.castToHTML(activityDetail);
            }
            modelAndView.addObject("activityDetail", activityDetail);
            modelAndView.addObject("activity", activity);


            String address = activityService.getShowAddress(activity);
            modelAndView.addObject("address", address);
            modelAndView.addObject("crowdfundEvent", crowdfundEvent);
            List<Counterfoil> counterfoils = counterfoilService.findByBusinessId(eventId, Constant.BUSINESS_TYPE_CROWDFUND);
            modelAndView.addObject("counterfoils", counterfoils);

        } else {
            CrowdfundEvent query = new CrowdfundEvent();
            query.setProgress(YesNoStatus.YES.getCode()); // 进行中
            List<CrowdfundEvent> events = crowdfundEventService.list(query);
            modelAndView.addObject("crowdfundEventList", events);
        }
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("getData")
    public AjaxResult getData(String eventId) {
        if (StringUtils.isEmpty(eventId)) {
            return AjaxResult.error("id不能为空");
        }
        Map<String, Object> resultMap = Maps.newHashMap();
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(eventId);
        Activity activity = new Activity();
        try {
            MyBeanUtils.copyBeanNotNull2Bean(crowdfundEvent, activity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        activity.setId(null);
        activity.setEventId(eventId);
        //个人众筹页状态，0:显示所属主题报名人员,1:显示该项目报名人员,2:不显示
        activity.setPersonalPopularPageState(0);
        activity.setTitle(crowdfundEvent.getName());
        // 跑马灯
        List<CrowfundResources> picList = crowfundResourcesService.findByRefId(crowdfundEvent.getId(), "1");
        resultMap.put("picList", picList);
        // 视频
        List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(crowdfundEvent.getId(), "2");
        if (videoList.size() > 0) {
            resultMap.put("video", videoList.get(0));
        }
        //项目海报
        activity.setIsCopartner(crowdfundEvent.getIsCustomPoster());
        activity.setNetworkImagePath(crowdfundEvent.getNetworkImagePath());

        List<Counterfoil> counterfoils = counterfoilService.findByBusinessId(eventId, Constant.BUSINESS_TYPE_CROWDFUND);
        resultMap.put("counterfoils", counterfoils);

        /** 活动详情 **/
        ActivityDetail activityDetail = activityDetailService.getByRefId(crowdfundEvent.getId());
        if (activityDetail != null) {
            activityDetailBizService.castToHTML(activityDetail);
        }
        resultMap.put("activityDetail", activityDetail);
        resultMap.put("activity", activity);

        String address = activityService.getShowAddress(activity);
        resultMap.put("address", address);
        if (activity.getStartTime() != null) {
            String startDate = DateUtils.formatDate(activity.getStartTime(), "yyyy-MM-dd HH:mm");
            resultMap.put("startDate", startDate);
        }
        if (activity.getEndTime() != null) {
            String endDate = DateUtils.formatDate(activity.getEndTime(), "yyyy-MM-dd HH:mm");
            resultMap.put("endDate", endDate);
        }
        if (YesNoStatus.YES.getCode().equals(crowdfundEvent.getIsMultiple())) {
            List<EventGradation> eventGradations = eventGradationService.withCityNameByEventId(crowdfundEvent.getId());
            resultMap.put("eventGradations", eventGradations);
        }
        resultMap.put("isMultiple", crowdfundEvent.getIsMultiple());

        MemberGroup createMember = memberGroupService.get(crowdfundEvent.getCreateBy());
        resultMap.put("createMember", createMember);
        resultMap.put("isExpire", MemberFormUtil.isExpire(crowdfundEvent.getCreateBy(), null));

        Date expireTime = MemberFormUtil.getExpirationTimeById(crowdfundEvent.getCreateBy());
        if (null != expireTime) {
            resultMap.put("expireTime", DateUtils.formatDate(expireTime, DateUtils.DATETIME_PATTERN));
        }
        return AjaxResult.success(resultMap);
    }

    @Autowired
    private MemberBizService memberBizService;

    /**
     * 获取主题下项目已分配的合伙人
     *
     * @param eventId 主题id
     * @return
     */
    @ResponseBody
    @RequestMapping("getCopartnerByEvent")
    public AjaxResult getCopartnerByEvent(String eventId) {
        if (StringUtils.isEmpty(eventId)) {
            return AjaxResult.error("主题id不能为空");
        }
        List<Map<String, Object>> copartnerList = activityService.getActivityCopartner(eventId);
        String memberId = RealmUtils.getCurrentUser().getId();
        for (Map<String, Object> mmp : copartnerList) {
            //替换手机号
            String phone = memberBizService.replacePhone(memberId, mmp.get("mobile").toString());
            mmp.put("mobile", phone);
        }
        return AjaxResult.success(copartnerList);
    }

    /**
     * 复制众筹项目视图
     *
     * @param id 编号
     * @return 交互数据
     */
    @RequestMapping(value = "copyView")
    public ModelAndView copyView(String id, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/eventView");
        City city = new City();
        city.setIsOpen(1);
        modelAndView.addObject("citys", cityService.list(city));


        List<Audio> audioList = null;
        //背景乐
        try {
            audioList = audioService.list(new Audio(null, com.party.common.constant.Constant.IS_CROWDFUNDED, null));
        } catch (Exception e) {
            logger.info("众筹主题详情页————获取背景乐列表失败", e.getMessage());
        }
        modelAndView.addObject("audioList", audioList);


        if (!Strings.isNullOrEmpty(id)) {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(id);
            crowdfundEvent.setId(null);
            if (StringUtils.isNotEmpty(crowdfundEvent.getSupportRange())) {
                if (crowdfundEvent.getSwitchSupportRange() == 3) {
                    String[] ranges = crowdfundEvent.getSupportRange().split(",");
                    crowdfundEvent.setRangeStart(Integer.valueOf(ranges[0]));
                    crowdfundEvent.setRangeEnd(Integer.valueOf(ranges[1]));
                    crowdfundEvent.setSupportRange("");
                }
            }

            City c = cityService.get(crowdfundEvent.getCityId());
            if (null != c) {
                modelAndView.addObject("cityName", c.getName());
            }

            List<Counterfoil> counterfoils = counterfoilService.findByBusinessId(id, Constant.BUSINESS_TYPE_CROWDFUND);
            for (Counterfoil counterfoil : counterfoils) {
                counterfoil.setId(null);
                counterfoil.setBusinessId(null);
                counterfoil.setJoinNum(0);
            }
            modelAndView.addObject("counterfoils", counterfoils);

            // 跑马灯
            List<CrowfundResources> picList = crowfundResourcesService.findByRefId(id, "1");
            modelAndView.addObject("picList", picList);
            // 视频
            List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(id, "2");
            if (videoList.size() > 0) {
                modelAndView.addObject("video", videoList.get(0));
            }

            /** 活动详情 **/
            ActivityDetail activityDetail = activityDetailService.getByRefId(id);
            activityDetail.setId(null);
            if (activityDetail != null) {
                activityDetailBizService.castToHTML(activityDetail);
            }
            modelAndView.addObject("activityDetail", activityDetail);
            modelAndView.addObject("event", crowdfundEvent);

            Activity activity = activityService.countForEventId(id);
            modelAndView.addObject("eventActivity", activity);
            modelAndView.addObject("isCopy", 1);
        }
        return modelAndView;
    }

    /**
     * 初始化绑定手机页面二维码
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("initBindQrCode")
    public AjaxResult initBindQrCode() {
        try {
            List<CrowdfundEvent> events = crowdfundEventService.list(new CrowdfundEvent());
            for (CrowdfundEvent crowdfundEvent : events) {
                try {
                    Integer result = DateUtils.compareDate(new Date(), crowdfundEvent.getEndTime());
                    if (1 == result) {
                        continue;
                    }

                    // 普通活动
                    String filePath = fileBizService.getUploadCIPath(crowdfundEvent.getCreateBy(), "zcEvent");
                    String content = "project/bind_event.html?id=" + crowdfundEvent.getId();
                    fileBizService.uploadCloudOut(crowdfundEvent.getId(), filePath, content, crowdfundEvent.getCreateBy());
                } catch (Exception e) {
                    logger.error("主题绑定手机号二维码生成异常", e);
                    continue;
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("初始化绑定手机页面二维码页面", e);
            return AjaxResult.error("初始化绑定手机页面二维码异常");
        }
    }

    /**
     * 审核通过当前众筹主题
     *
     * @param event
     * @return
     */
    @Transactional
    @ResponseBody
    @RequestMapping("checkPass")
    public AjaxResult checkPass(CrowdfundEvent event) {
        try {
            if (StringUtils.isEmpty(event.getId())) {
                return AjaxResult.error("审核主题ID为空");
            }

            Double serviceCharge = event.getServiceCharge();
            if (serviceCharge != null && serviceCharge != 0d) {
                if (serviceCharge < 0.01d) {
                    return AjaxResult.error("主题服务费不能底于0.01,请重新设置");
                }

                CrowdfundEvent crowdfundEvent = crowdfundEventService.get(event.getId());
                Float price = crowdfundEvent.getPrice();
                if (YesNoStatus.NO.getCode().equals(crowdfundEvent.getIsMultiple())) {
                    Counterfoil counterfoil = new Counterfoil();
                    counterfoil.setBusinessId(event.getId());
                    counterfoil.setBusinessType(Constant.BUSINESS_TYPE_CROWDFUND);
                    Counterfoil minPriceCounterfoil = counterfoilService.getMinPriceCounterfoil(counterfoil);

                    if (null == minPriceCounterfoil) {
                        return AjaxResult.error("票据为空");
                    }

                    price = minPriceCounterfoil.getPayment();
                }
                BigDecimal newServiceCharge = new BigDecimal(serviceCharge);
                BigDecimal newPrice = new BigDecimal(price);
                double d1 = BigDecimalUtils.round(newServiceCharge.doubleValue(), 2);
                double d2 = BigDecimalUtils.round(Double.valueOf(newPrice.floatValue()), 2);
                if (d1 >= d2) {
                    return AjaxResult.error("主题服务费不能高于报名费,请重新设置");
                }
            }
            event.setCheckStatus(1);
            crowdfundEventService.update(event);//主题审核通过
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("当前主题审核通过失败", e);
            return AjaxResult.error("当前主题审核通过异常");
        }
    }

    /**
     * 审核拒绝当前众筹主题
     *
     * @param event
     * @return
     */
    @Transactional
    @ResponseBody
    @RequestMapping("checkRefuse")
    public AjaxResult checkRefuse(CrowdfundEvent event) {
        try {
            if (StringUtils.isEmpty(event.getId())) {
                return AjaxResult.error("审核主题ID为空");
            }
            event.setCheckStatus(2);
            event.setUpdateDate(new Date());
            crowdfundEventService.update(event);//主题审核拒绝
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("当前主题审核通过失败", e);
            return AjaxResult.error("当前主题审核通过异常");
        }
    }

    @ResponseBody
    @RequestMapping(value = "exportMerchantData")
    public AjaxResult exportMerchantData(String eventId, HttpServletRequest request) {
        if (StringUtils.isEmpty(eventId)) {
            return AjaxResult.error("主题id不能为空");
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                crowdfundEventBizService.exportMerchantData(eventId, request.getSession().getId());
            }
        }).start();
        return AjaxResult.success();
    }

    /**
     * @return
     * @author yifeng
     * @Description 初始化主题的金额为空的主题，金额设为最小的金额
     * @date 10:34 2019/7/8
     **/
    @ResponseBody
    @RequestMapping(value = "initPriceIsNullEvent")
    public AjaxResult initPriceIsNullEvent() {
        List<CrowdfundEvent> crowdfundEvents = crowdfundEventService.getPriceIsNull();
        for (CrowdfundEvent event : crowdfundEvents) {
            List<Counterfoil> counterfoils = counterfoilService.findByBusinessId(event.getId(),
                    Constant.BUSINESS_TYPE_CROWDFUND);
            if (counterfoils.size() == 0) {
                continue;
            }
            CrowdfundEvent db = crowdfundEventService.get(event.getId());
            if (counterfoils.size() == 1) {
                db.setPrice(counterfoils.get(0).getPayment());
            } else {
                Collections.sort(counterfoils, new Comparator<Counterfoil>() {
                    @Override
                    public int compare(Counterfoil o1, Counterfoil o2) {
                        if (o1.getPayment() < o2.getPayment()) {
                            return -1;
                        } else {
                            return 1;
                        }
                    }
                });
                db.setPrice(counterfoils.get(0).getPayment());
            }
            crowdfundEventService.update(db);
        }
        return AjaxResult.success();
    }
}
